#include "handler.h"
#include "server.h"
#include "raw_command.h"
#include "sys_socket.h"
#include <map>
#include <iostream>
using std::cout;
using std::endl;
using std::map;

ClientHandler::ClientHandler(int sock)
    :m_sock(sock),
     m_reader(m_sock)
{
}

ClientHandler::~ClientHandler()
{
    stop();
}

void ClientHandler::run()
{
    while (true) {
        RawCommand rc;
        if (getRawCommand(rc)) {
            handleRawCommand(rc);
        } else {
            cout << "Connection lost" << endl;
            break;
        }
    }
}

void ClientHandler::stop()
{
    if (m_sock != -1) {
        lock();
        closesocket(m_sock);
        m_sock = -1;
        unlock();
        join();
    }
}

bool ClientHandler::getRawCommand(RawCommand& rc)
{
    // get command header
    while (true) {
        string str;
        if (m_reader.getLine(str)) {
            if (str.length() <= 2) {
                break;
            } else {
                rc.setValue(str);
            }
        } else {
            // failed to get a string
            return false;
        }
    }
    // get msg body
    unsigned int nBytes = 0;
    while (nBytes < rc.getContentLength()) {
        char chr;
        if (m_reader.getChar(chr)) {
            rc.addContentByte(chr);
            nBytes++;
        } else {
            return false;
        }
    }
    return true;
}

void ClientHandler::handleRawCommand(RawCommand& rc)
{
    cout << "ClientHandler::handleRawCommand: " << endl;
    map<string, string> const & keywords = rc.getKeywords();
    map<string, string>::const_iterator iter = keywords.begin();
    while (iter != keywords.end()) {
        cout << iter->first << " - " << iter->second << endl;
        ++iter;
    }
}
